package com.httpDemo.config;

import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;

import lombok.Data;

/**
 * 自定义druid数据源配置类
 * 
 * @author Administrator
 *
 */
@Data
//@Configuration // 要用的话，需打开该注解
@ConditionalOnClass({ DruidDataSource.class })
@ConfigurationProperties(prefix = "spring.druid.param")
public class DruidAutoConfiguration {

	private String urlMappings;
	private String loginUsername;
	private String loginPassword;
	private String allow;
	private String deny;

	@Bean(initMethod = "init")
	@ConfigurationProperties(prefix = "spring.druid")
	public DruidDataSource dataSource() {
		DruidDataSource dataSource = new DruidDataSource();
		return dataSource;
	}

	/**
	 * 配置监控页面
	 * 
	 * @return
	 */
	@Bean
	public ServletRegistrationBean<StatViewServlet> servletRegistrationBeanStatViewServlet() {
		// 创建servlet
		StatViewServlet statViewServlet = new StatViewServlet();
		// 创建注册器
		ServletRegistrationBean<StatViewServlet> registrationBean = new ServletRegistrationBean<>();
		// 注入servlet
		registrationBean.setServlet(statViewServlet);
		// 注入url
		registrationBean.addUrlMappings(urlMappings);
		// 注入用户名参数
		registrationBean.addInitParameter(StatViewServlet.PARAM_NAME_USERNAME, loginUsername);
		// 注入密码参数
		registrationBean.addInitParameter(StatViewServlet.PARAM_NAME_PASSWORD, loginPassword);
		// 注入白名单参数，为空代表所有ip都可以访问
		registrationBean.addInitParameter(StatViewServlet.PARAM_NAME_ALLOW, allow);
		// 注入黑名单参数，为空代表所有ip都可以访问
		registrationBean.addInitParameter(StatViewServlet.PARAM_NAME_DENY, deny);
		return registrationBean;
	}
}
